// import type {DriverCardListItem} from ''
// // 该详情也要区分 是boss 还是 企业/协会
// const drawerConfig = useMemo(
//   () => ({
//     title: '计划详情',
//     width: DRAWERWIDTH,
//     open: drawerOpen,
//     onClose: () => {
//       setDrawerOpen(false);
//     },
//     destroyOnClose: true,
//     children: curPlanCourseId && currPlanType && (
//       <StudyPlanDetail planCourseId={curPlanCourseId} planType={currPlanType} />
//     ),
//   }),
//   [curPlanCourseId, drawerOpen, currPlanType],

// import type { DriverCardListItem, DriverCardListSearchParams } from '@/api/OfflineStudy';
import { exportStudyCardList } from '@/api/aiStudyApi';
import { filingEntList } from '@/api/codeApi';
import type { DriverCardListItem, DriverCardListSearchParams } from '@/api/OfflineStudy';
import { editExpireApi, getCardNumValue, secDriverCardList } from '@/api/OfflineStudy';
import CusDrawer from '@/components/CusDrawer';
import CusModal from '@/components/CusModal';
import { WaitDealContext } from '@/layouts/BasicLayout';
import { useAppSelector } from '@/redux/store';
import { maskIdCard } from '@/utils';
import { useRequest } from 'ahooks';
import { App, Button, Checkbox, Form, message, Space } from 'antd';
import React, { useContext, useEffect, useMemo, useRef, useState } from 'react';
import { useSearchParams } from 'react-router-dom';
import type { YmColumnsType } from 'ym-design';
import { YmTable } from 'ym-design';
import DriverCardDetail from './components/DriverCardDetail';
import EditExpireModal from './components/EditExpireModal';
import { OrgTree } from './components/OrgTree';
type SearchValue = Partial<DriverCardListSearchParams>;
type TableRecord = DriverCardListItem & { showEditButton?: boolean };
export type AssFilterType = {
  orgId: string;
  includeSub: number;
};

function CheckboxItem(props: { value?: boolean; onChange?(value: number): void }) {
  const { value, onChange } = props;

  return (
    <Checkbox checked={!!value} onChange={(e) => onChange?.(+e.target.checked)}>
      包含下级监管机构数据
    </Checkbox>
  );
}

// );
const DRAWERWIDTH = 750;
export default function DriverCardList() {
  const [sp] = useSearchParams();
  const urlIncludeSub = sp.get('includeSub');
  const { entName } = useAppSelector((state) => state.loginEnt);
  const type = sp.get('type');
  // const { entId } = useAppSelector((state) => state.loginEnt);
  const [refreshFlag, _setRefreshFlag] = useState(false);
  const [curCardId, setCurCardId] = useState<string>();
  const [drawerOpen, setDrawerOpen] = useState(false);
  const EditExpireRef = useRef<any>(null);
  const [studyCardNum, setStudyCardNum] = useState<any>({
    allNum: 0,
    expiredNum: 0,
    normalNum: 0,
    willExpireNum: 0,
    untrainedNum: 0,
  });
  const [configModal, setConfigModal] = useState<{ title: string; children: React.ReactNode }>();
  const [modalBtnStatus, setModalBtnStatus] = useState({ loading: false, disabled: false }); //modal框按钮状态
  const [isModalShow, setIsModalShow] = useState<{ show: boolean }>({ show: false });
  const [activeKey, setActiveKey] = useState(type === 'expired' ? '2' : '0');
  const [assFilter, setAssFilter] = useState<AssFilterType>({
    orgId: '',
    includeSub: urlIncludeSub ? Number(urlIncludeSub) : 1,
  });
  const [page, setPage] = useState<any>({});

  const [isTemporary, setIsTemporary] = useState<number>();

  const [form] = Form.useForm();
  const includeSub = Form.useWatch('includeSubordinateData', form);
  useEffect(() => {
    form.setFieldValue('entId', '');
  }, [includeSub]);

  const {
    modal: { confirm },
  } = App.useApp();
  // 刷新table的 flag
  function refreshTable() {
    _setRefreshFlag((v) => !v);
  }

  // useEffect(() => {
  //   getBelongEntlistApi(entId).then((res: any) => {
  //     setTotalEntNum(res.data.driverTotal);
  //     setEntVoList(res.data.entVoList);
  //   });
  // }, []);

  const { data: entList } = useRequest(
    async () => {
      const { data } = await filingEntList({
        associationId: assFilter.orgId,
        includeSubordinateData: includeSub,
      });
      return [
        {
          label: '全部',
          value: '',
        },
        ...data.map((item: any) => ({
          label: item.name,
          value: item.entId,
        })),
      ];
    },
    {
      ready: !!assFilter.orgId,
      refreshDeps: [assFilter, includeSub],
    },
  );

  // 打开编辑过期时间
  const openEditExpirModal = (param: any) => {
    setIsModalShow({ show: true });
    setConfigModal({
      title: '更改有效期',
      children: <EditExpireModal ref={EditExpireRef} {...param} />,
    });
  };
  async function regetNum(obj: any, pageIndex: number | undefined, pageSize: number | undefined) {
    const result: any = await getCardNumValue(obj, pageIndex, pageSize);
    setStudyCardNum(result);
  }
  const columns: YmColumnsType<TableRecord> = useMemo(
    () => [
      {
        title: '司机姓名',
        dataIndex: 'personName',
        key: 'personName',
        width: 180,
        render: (text, record) => (
          <div style={{ display: 'flex', alignItems: 'center' }}>
            <span>{text ?? '--'}</span>
            {Boolean(record?.isTemporary) && (
              <>
                <div
                  style={{
                    color: 'pink',
                    cursor: 'pointer',
                    marginLeft: 5,
                    display: 'flex',
                    alignItems: 'center',
                    height: '16px',
                    borderRadius: '2px',
                    border: '1px solid #F66E2C',
                  }}
                >
                  <span
                    style={{
                      paddingLeft: '4px',
                      paddingRight: '4px',
                      fontWeight: 400,
                      fontSize: '12px',
                      color: '#F66E2C',
                    }}
                  >
                    临时备案
                  </span>
                </div>
              </>
            )}
          </div>
        ),
      },
      {
        title: '电话',
        dataIndex: 'phone',
        key: 'phone',
        width: 100,
      },
      {
        title: '身份证号码',
        dataIndex: 'idCardNo',
        key: 'idCardNo',
        width: 160,
        render(v) {
          return v ? maskIdCard(v) : '--';
        },
      },
      {
        title: '企业',
        dataIndex: 'entName',
        key: 'entName',
        width: 180,
        ellipsis: true,
      },
      {
        title: '学习卡状态',
        dataIndex: 'state',
        key: 'state',
        width: 90,
        render: (_text, record) => {
          return (
            <div>
              {_text == 1 ? (
                <span style={{ color: '#33CC67', display: 'flex', alignItems: 'center' }}>
                  <span
                    style={{
                      display: 'inline-block',
                      width: 4,
                      height: 4,
                      background: '#33CC67',
                      borderRadius: '8px',
                      marginRight: 3,
                    }}
                  ></span>
                  正常
                </span>
              ) : _text == 3 ? (
                <span style={{ color: '#f96767', display: 'flex', alignItems: 'center' }}>
                  <span
                    style={{
                      display: 'inline-block',
                      width: 4,
                      height: 4,
                      background: '#f96767',
                      borderRadius: '8px',
                      marginRight: 3,
                    }}
                  ></span>
                  即将过期
                </span>
              ) : (
                <span style={{ color: '#999999', display: 'flex', alignItems: 'center' }}>
                  <span
                    style={{
                      display: 'inline-block',
                      width: 4,
                      height: 4,
                      background: '#999999',
                      borderRadius: '8px',
                      marginRight: 3,
                    }}
                  ></span>
                  已过期
                </span>
              )}
            </div>
          );
        },
      },
      {
        title: '学习卡有效期',
        dataIndex: 'startTime',
        key: 'startTime',
        width: 120,
        render: (_text, record) => {
          return (
            <div>
              {record.startTime || '--'}至{record.endTime || '--'}
            </div>
          );
        },
      },
      {
        title: '操作',
        key: 'action',
        width: 100,
        fixed: 'right',
        render: (_text, record) => {
          return (
            <Space direction="horizontal" size={0}>
              <Button
                type="text"
                size="small"
                onClick={(e: React.MouseEvent) => {
                  // console.log(record, '123');
                  // e.stopPropagation();
                  // setCurCardId(record.studyCardId);
                  // setDrawerOpen(true);
                  openEditExpirModal(record);
                }}
              >
                <span className="safe-edu_table_operation_text">更改</span>
              </Button>
              <Button
                type="text"
                size="small"
                onClick={(e: React.MouseEvent) => {
                  e.stopPropagation();
                  setCurCardId(record.studyCardId);
                  // setCurrPlanType(record.type);
                  setDrawerOpen(true);

                  if (record?.isTemporary) {
                    setIsTemporary(1);
                  }
                }}
              >
                <span className="safe-edu_table_operation_text">详情</span>
              </Button>
            </Space>
          );
        },
      },
    ],
    [refreshFlag, curCardId],
  );
  const drawerConfig = useMemo(
    () => ({
      title: (
        <div style={{ display: 'flex', alignItems: 'center' }}>
          <span>详情</span>
          {Boolean(isTemporary) && (
            <>
              <div
                style={{
                  cursor: 'pointer',
                  marginLeft: 5,
                  display: 'flex',
                  alignItems: 'center',
                  height: '16px',
                  borderRadius: '2px',
                  border: '1px solid #F66E2C',
                }}
              >
                <span
                  style={{
                    paddingLeft: '4px',
                    paddingRight: '4px',
                    fontWeight: 400,
                    fontSize: '12px',
                    color: '#F66E2C',
                  }}
                >
                  临时备案
                </span>
              </div>
            </>
          )}
        </div>
      ),
      width: DRAWERWIDTH,
      open: drawerOpen,
      onClose: () => {
        setDrawerOpen(false);
      },
      destroyOnClose: true,
      children: curCardId && <DriverCardDetail curCardId={curCardId} refreshTable={refreshTable} />,
    }),
    [curCardId, drawerOpen],
  );

  // 关闭modal
  const closeModal = () => {
    setIsModalShow({ show: false });
  };

  //点击modal保存按钮
  const confirmModal = () => {
    setModalBtnStatus({ disabled: true, loading: true });
    EditExpireRef.current?.onSubmit().then((values: any) => {
      const upTime = values.endTime.format('YYYY-MM-DD');
      confirm({
        title: '提示',
        width: '450px',
        content: '您确定要更改 ' + values.personName + ' 的学习卡有效期至 ' + upTime + ' 吗？',
        centered: true,
        onOk: () => {
          editExpireApi({ ...values, upTime }).then((res: any) => {
            if (res.code == 200) {
              message.success('更改成功');
              refreshTable();
              closeModal();
            }
          });
        },
      });
    });
    // .finally((error: any) => {
    //   console.log(error, '走没走这里');
    //   setModalBtnStatus({ disabled: false, loading: false });
    //   closeModal();
    // });
    setModalBtnStatus({ disabled: false, loading: false });
  };
  const { flyInStart, requestFlyIn } = useContext(WaitDealContext);
  const { run: handleExport, loading: expoLoading } = useRequest(
    async (e) => {
      const value = form?.getFieldsValue();
      const state = activeKey === '0' ? undefined : Number(activeKey);
      const formValue = Object.fromEntries(
        Object.entries(value).filter(([k, v]: any[]) => ![undefined, null, ''].includes(v)),
      );
      const params = {
        state,
        associationId: assFilter.orgId,
        pageNum: page?.pageIndex || 1,
        pageSize: page?.pageSize || 10,
        ...formValue,
      };

      requestFlyIn(e, '学习卡统计', exportStudyCardList, params).then((res: any) => {
        if (res.suc) {
          //success doing
        }
      });
    },
    { manual: true },
  );

  // modal框配置
  const modalConst = {
    open: isModalShow.show,
    width: 450,
    // centered: true,
    destroyOnClose: true,
    footer: [
      <Button key="back" disabled={modalBtnStatus.disabled} onClick={closeModal}>
        取消
      </Button>,
      <Button type="primary" key="save" loading={modalBtnStatus.loading} onClick={confirmModal}>
        保存
      </Button>,
    ],
    onCancel: closeModal,
  };

  const onSelect = (org: any) => {
    setAssFilter((v: AssFilterType) => ({
      ...v,
      orgId: org.entId,
    }));
  };
  return (
    <div className="safe_boss_pagelr">
      <CusDrawer {...drawerConfig} />
      <CusModal {...modalConst} {...configModal} />

      <div className="safe_boss_page_left">
        {/* <div>
          <div
            className={`${Ostyle.menu_li} ${currentIndex == 0 ? Ostyle.active : null}`}
            onClick={() => {
              setCurrentIndex(0);
              setSelEntId('');
              refreshTable();
            }}
          >
            全部({totalEntNum})
          </div>
          <div className={Ostyle.menu_cont}>
            {entVoList.map((el: any) => {
              return (
                <div
                  key={el.entId}
                  className={`${Ostyle.menu_li} ${currentIndex == el.entId ? Ostyle.active : null}`}
                  onClick={() => {
                    setCurrentIndex(el.entId);
                    setSelEntId(el.entId);
                    refreshTable();
                  }}
                >
                  <div className={Ostyle.li_entname} title={el.entName}>
                    {el.entName}
                  </div>
                  （{el.driverNum}）
                </div>
              );
            })}
          </div>
        </div> */}
        <OrgTree orgId={assFilter.orgId} setOrg={onSelect} type="person" />
      </div>
      <div className="safe_boss_page_right">
        <YmTable<TableRecord, SearchValue>
          rowKey="studyCardId"
          columns={columns}
          toolBar={{
            prefixNode: (
              <Button
                onClick={(e) => {
                  handleExport(e);
                }}
              >
                导出Excel
              </Button>
            ),
          }}
          searchForm={{
            form,
            initialValues: {
              entId: '',
              includeSubordinateData: urlIncludeSub ? Number(urlIncludeSub) : 1,
            },
            formItems: [
              {
                name: 'personName',
                label: '司机姓名',
                valueType: {
                  inputProps: {
                    autoComplete: 'off',
                  },
                },
              },
              {
                name: 'phone',
                label: '电话号码',
                valueType: {
                  inputProps: {
                    autoComplete: 'off',
                  },
                },
              },
              {
                label: '备案企业',
                name: 'entId',
                valueType: {
                  type: 'select',
                  selectProps: {
                    options: entList,
                  },
                },
              },
              {
                name: 'includeSubordinateData',
                children: <CheckboxItem />,
              },
              // {
              //   name: 'studyObject',
              //   label: '学习卡状态',
              //   valueType: {
              //     selectProps: {
              //       options: STUDYCARDSTATEOPTIONS,
              //       showSearch: false,
              //       maxTagCount: 1,
              //     },
              //   },
              // },
            ],
          }}
          tabs={{
            activeKey,
            onChange(key) {
              setActiveKey(key);
            },
            items: [
              {
                label: '全部（' + studyCardNum.allNum + '）',
                key: '0',
              },
              {
                label: '正常（' + studyCardNum.normalNum + '）',
                key: '1',
              },
              {
                label: '即将过期（' + studyCardNum.willExpireNum + '）',
                key: '3',
              },
              {
                label: '已过期-时间到期（' + studyCardNum.expiredNum + '）',
                key: '2',
              },
              {
                label: '已过期-从未培训（' + studyCardNum.untrainedNum + '）',
                key: '4',
              },
            ],
          }}
          request={async ({ page }, value = {}) => {
            const state = activeKey === '0' ? undefined : Number(activeKey);
            if (!assFilter.orgId) return { list: [], total: 0 };
            regetNum({ ...value, state, associationId: assFilter.orgId }, page?.pageIndex, page?.pageSize); // 获取tab数量
            setPage(page);
            const result = await secDriverCardList(
              { ...value, state, associationId: assFilter.orgId },
              page?.pageIndex,
              page?.pageSize,
            );
            // result.list = [
            //   {
            //     personName: 'ddd',
            //     phone: '3233333',
            //     entName: '33333',
            //     state: 1,
            //     startTime: '2023-12-11 10:00',
            //     endTime: '2024-12-23 11: 00',
            //   },
            //   {
            //     personName: 'dxr',
            //     phone: '1233333',
            //     entName: '33333',
            //     state: 2,
            //     startTime: '2023-11-11 10:00',
            //     endTime: '2024-11-23 11: 00',
            //   },
            // ];
            return {
              list: result.list.map((listItem: TableRecord) => {
                // const { type, openStatus, startTime, status } = listItem;
                // let showEditButton = true;
                // if (type === '100') {
                //   //固定时间
                //   if (openStatus === 1) {
                //     //开启的话，不能编辑
                //     showEditButton = false;
                //   } else {
                //     // 关闭状态下
                //     if (dayjs().isAfter(startTime)) {
                //       //当前时间大于已开始时间，则不可编辑
                //       showEditButton = false;
                //     }
                //   }
                // }
                // // 循环计划，任何状态都能编辑
                // if (status === 300 || status === 400) showEditButton = false;
                return {
                  ...listItem,
                  // showEditButton,
                };
              }),
              total: result.total,
            };
          }}
          requestOptions={{
            reFreshDep: [refreshFlag, assFilter],
          }}
        />
      </div>
    </div>
  );
}
